#include "systime.h"
#include "hc_log.h"
#include "my_define.h"
#include "timeout_conf.h"
#include "radio/radio.h"

volatile u32 g_nSysTickCount = 0;

#define RF_PACKET_SIZE 20 /* Define the payload size here */

static u8 g_rxBuffer[RF_PACKET_SIZE + 1]; /* RF Rx buffer */
static u8 g_txBuffer[RF_PACKET_SIZE];     /* RF Tx buffer */

u32 g_nRecvCount = 0, g_nSendCount = 0;


void App_ClkCfg(void)
{
    // 使用38.4K的RCL作为系统时钟源
    ///< 系统时钟源初始化
    stc_sysctrl_sysclk_source_init_t stcSysClkSrc = {0};
    stcSysClkSrc.u32SysClkSourceType = SYSCTRL_SYSCLK_SOURCE_TYPE_RCL;
    stcSysClkSrc.u32RCLState = SYSCTRL_RCL_TRIM_38p4KHz |
                               SYSCTRL_RCL_WAITCYCLE256;

    SYSCTRL_SysClkSrcInit(&stcSysClkSrc);
}
u8 Radio_Send_FixedLen(const u8 pBuf[], u8 len)
{
    u8 wrLen = 0;
    u32 delay;
    CMT2300A_GoStby();
#ifdef ENABLE_ANTENNA_SWITCH
    /* Config interrupt */
    CMT2300A_ConfigInterrupt(
        CMT2300A_INT_SEL_PKT_DONE, /* Config INT1 */
        CMT2300A_INT_SEL_TX_DONE   /* 将INT2上的GPIO3设置为发射完成中断onfig INT2 */
    );
#endif
    CMT2300A_ClearInterruptFlags();
    CMT2300A_EnableWriteFifo();
    CMT2300A_ClearTxFifo();
    CMT2300A_SetPayloadLength(len);
    CMT2300A_WriteFifo(pBuf, len); // 写 TX_FIFO
    if (CMT2300A_GoTx() == 0)
        return 0; // 状态切换NG
    delay = 3000;
    while (1)
    {
#ifdef ENABLE_ANTENNA_SWITCH
        if (CMT2300A_ReadGpio3()) // 300H只能有GPIO3做发射完成中断
#else
        if (CMT2300A_ReadGpio1()) // TX_DONE
#endif
        // if(CMT2300A_MASK_TX_DONE_FLG & CMT2300A_ReadReg(CMT2300A_CUS_INT_CLR1))  /* Read TX_DONE flag */
        {
            CMT2300A_GoStby();
            CMT2300A_ClearInterruptFlags();
            CMT2300A_GoSleep();
            return 1; //
        }

        if (delay == 0) // 超时溢出
        {
            CMT2300A_GoStby();
            CMT2300A_ClearInterruptFlags();
            CMT2300A_GoSleep();
            return 0; // 发送超时
        }
        system_delay100us(2);
        delay--;
    }
}
void radio_send()
{
    static timestamp_t send_time;
    if(is_relative_time_timeout(&send_time))
    {
        relative_time_add_ms(&send_time, 2000);
        if (Radio_Send_FixedLen(g_txBuffer, (RF_PACKET_SIZE / 2)) == 1)
        {
            g_nSendCount++;
        }
        else
        {
            RF_Init(); // 异常处理
        }
    }
}
// TX
int main(void)
{
    int i;
    g_nSendCount = 0;

    for (i = 0; i < RF_PACKET_SIZE; i++)
        g_txBuffer[i] = 1 + i;
    App_ClkCfg();
    systime_init();
    SysTick_Config(3950);
    RF_Init();
    if (FALSE == CMT2300A_IsExist())
    {
        while (1)
        {
        }
    }

    while (1)
    {
        radio_send();
        systime_enter_sleep();
    }
}
void SysTick_IRQHandler(void)
{
    g_nSysTickCount++;
}
